package com.sunwhite.herostore.common;

import com.sunwhite.herostore.msg.GameMsgProtocol;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public final class BroadCaster {
    /***
     *方法不能继承和私有化
     */
    private BroadCaster(){
    }
    /**
     * 客户端信道数组, 一定要使用 static, 否则无法实现群发
     */
    private static final ChannelGroup _channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 添加通信连接通道
     * @param channel
     */
    public static void addChannel(Channel channel){
        _channelGroup.add(channel);
    }

    /**
     * 在组内群发消息
     * @param msg
     */
    public static void broadCast(Object msg){
        _channelGroup.writeAndFlush(msg);
    }

    /**
     * 移除一条通信连接通道
     * @param channel
     */
    public static void remove(Channel channel){
        _channelGroup.remove(channel);
    }

    /**
     * 广播用户离场消息
     * @param userId 用户Id
     */
    public static void broadQuit(Integer userId){
        if (null==userId){
            return;
        }
        GameMsgProtocol.UserQuitResult.Builder resultBuilder = GameMsgProtocol.UserQuitResult.newBuilder();
        resultBuilder.setQuitUserId(userId);
        GameMsgProtocol.UserQuitResult newResult = resultBuilder.build();
        broadCast(newResult);
    }

    /**
     * 广播用户死亡的消息
     * @param userId 死亡的用户ID
     */
    public static void broadDie(Integer userId){
        if(userId==null){
            return;
        }
        GameMsgProtocol.UserDieResult.Builder userDieResultBuilder = GameMsgProtocol.UserDieResult.newBuilder();
        userDieResultBuilder.setTargetUserId(userId);
        GameMsgProtocol.UserDieResult userDieResult = userDieResultBuilder.build();
        BroadCaster.broadCast(userDieResult);
    }

}
